<?php

namespace App\Http\Controllers;

use Validator;
use App\Models\Task;
use Illuminate\Http\Request;

class TaskController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index(Request $request)
  {
    $query = Task::where('name', 'like', '%'. $request->name .'%');
    if($request->show_all == 1) {
      $tasks = $query->get();
    } else {
      $tasks = $query->paginate(10);
    }
    return $this->success(0, '请求成功', $tasks);
  }

  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $validator = Validator::make($request->all(), [
      'name' => 'required|alpha_dash|between:1,100',
      'cd' => 'required|numeric|min:0',
      'status' => 'required|boolean',
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $cred = $request->only('name', 'cd', 'status');
    $task = Task::create($cred);
    return $this->success(0, '', $task);
  }

  /**
   * Update the specified resource in storage.
   *
   * @param  \Illuminate\Http\Request $request
   * @param  int $id
   * @return \Illuminate\Http\Response
   */
  public function update(Request $request, $id)
  {
    $validator = Validator::make($request->all(), [
      'name' => 'required|alpha_dash|between:1,100',
      'cd' => 'required|numeric|min:0',
      'status' => 'required|boolean',
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $cred = $request->only('name', 'cd', 'status');
    $task = Task::findOrFail($id);
    $task->update($cred);
    return $this->success(0, '更新成功！', $task);
  }

  /**
   * Remove the specified resource from storage.
   *
   * @param  int $id
   * @return \Illuminate\Http\Response
   */
  public function destroy($id)
  {
    $task = Task::findOrFail($id);
    $task->delete();
    return $this->success(0, '删除成功！');
  }
}
